package com.itheima.ydd.controller;

import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.FileDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@SuppressWarnings("All")
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResultData upload(MultipartFile file, String type) {

        //设定时间格式
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取右边图片文件类型
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //获取当前时间毫秒值，并组合成新文件名
        String fileName = date.getTime() + suffix;
        //获取存储路劲
        String savePath = "upload/" + type + "/" + simpleDateFormat.format(date.getTime()) + "/" + fileName;

        //测试用路劲
        // String path = basePath + simpleDateFormat.format(date.getTime());

        //封装Filedto对象
        FileDto fileDto = new FileDto();
        fileDto.setSavePath(savePath);
        fileDto.setName(originalFilename);
        fileDto.setSize(file.getSize());

        //判断文件上传类型
        if (type.equals("images")) {
            fileDto.setMime("image/" + suffix);
        }
        //创建一个目录对象
        File dir = new File(basePath + "undefined" + savePath);
        //创建一个测试目录对象
        //File dirtest = new File(path);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，重新创建
            dir.mkdirs();

        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + "undefined" + savePath));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultData.ok("",fileDto);
    }

}
